﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using IDAdmin.Lib.DataLayer;

namespace IDAdmin.Lib.Utils
{
    /// <summary>
    /// Lớp cung cấp các chức năng hỗ trợ cho việc giao tiếp thông qua HTTP
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// Gởi request đến link bằng phương thức GET. Hàm trả về chuỗi chứa kết quả được response từ link cần get dữ liệu
        /// </summary>
        /// <param name="link">URL và tham số (nếu có) cần get dữ liệu</param>
        /// <param name="timeToTry">Số lần thử lại nếu thất bại (0 nếu chỉ gọi 1 lần)</param>
        /// <returns></returns>
        public static string HttpGet(string link, int timeToTry)
        {
            string _result = "";
            try
            {
                System.Net.ServicePointManager.Expect100Continue = false;
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(link);
                httpRequest.Timeout = 60000; //60s
                int loopCount = 0;

                do
                {
                    loopCount += 1;
                    try
                    {
                        HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                        if (httpResponse.StatusCode == HttpStatusCode.OK)
                        {
                            Encoding responseEncoding = Encoding.GetEncoding(httpResponse.CharacterSet);
                            using (StreamReader sReader = new StreamReader(httpResponse.GetResponseStream(), responseEncoding))
                            {
                                _result = sReader.ReadToEnd();
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Thread.Sleep(1000);
                    }
                }
                while (loopCount <= timeToTry);
            }
            catch (Exception ex)
            {
            }
            return _result;
        }

        /// <summary>
        /// Gởi request đến link bằng phương thức POST
        /// </summary>
        /// <param name="link"></param>
        /// <param name="data"></param>
        /// <param name="timeToTry"></param>
        /// <returns></returns>
        public static string HttpPost(string link, string data, int timeToTry)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byteData = encoding.GetBytes(data);
            return HttpPost(link, byteData, timeToTry);
        }

        /// <summary>
        /// Gởi request đến link bằng phương thức POST
        /// </summary>
        /// <param name="link"></param>
        /// <param name="data"></param>
        /// <param name="timeToTry"></param>
        /// <returns></returns>
        public static string HttpPost(string link, byte[] data, int timeToTry)
        {
            string result = "";
            try
            {
                System.Net.ServicePointManager.Expect100Continue = false;
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(link);
                httpRequest.Timeout = 60000; //60s
                httpRequest.Method = "POST";
                httpRequest.ContentType = "application/x-www-form-urlencoded";
                httpRequest.ContentLength = data.Length;

                int loopCount = 0;

                do
                {
                    loopCount += 1;
                    try
                    {
                        Stream dataStream = httpRequest.GetRequestStream();
                        dataStream.Write(data, 0, data.Length);
                        dataStream.Close();
                        WebResponse httpResponse = httpRequest.GetResponse();
                        dataStream = httpResponse.GetResponseStream();
                        StreamReader reader = new StreamReader(dataStream);
                        result = reader.ReadToEnd();
                        reader.Close();
                        dataStream.Close();
                        httpResponse.Close();
                        break;
                    }
                    catch (Exception ex)
                    {
                        Thread.Sleep(100);
                    }

                }
                while (loopCount <= timeToTry);
            }
            catch (Exception ex)
            {
            }

            return result.Trim();
        }

        /// <summary>
        /// Get nội dung của một link web (tương tự hàm file_get_contents của PHP)
        /// </summary>
        /// <param name="link"></param>
        /// <returns></returns>
        public static string GetContents(string link)
        {
            try
            {
                string sContents = string.Empty;
                System.Net.WebClient wc = new System.Net.WebClient();
                byte[] response = wc.DownloadData(link);
                sContents = System.Text.Encoding.UTF8.GetString(response);
                return sContents;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        /// <summary>
        /// Gởi request đến link bằng phương thức GET. Hàm trả về chuỗi chứa kết quả được response từ link cần get dữ liệu
        /// </summary>
        /// <param name="link">URL và tham số (nếu có) cần get dữ liệu</param>
        /// <param name="timeToTry">Số lần thử lại nếu thất bại (0 nếu chỉ gọi 1 lần)</param>
        /// <returns></returns>
        public static string HttpGetOther(string link, int timeToTry)
        {
            string _result = "";
            try
            {
                System.Net.ServicePointManager.Expect100Continue = false;
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(link);
                httpRequest.Timeout = 60000; //60s
                int loopCount = 0;

                do
                {
                    loopCount += 1;
                    try
                    {
                        HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                        if (httpResponse.StatusCode == HttpStatusCode.OK)
                        {
                            Encoding responseEncoding = null;
                            try
                            {
                                responseEncoding = Encoding.GetEncoding(httpResponse.CharacterSet);
                            }
                            catch (Exception ex)
                            {
                                //if (string.IsNullOrEmpty(responseEncoding.ToString()))
                                //{
                                responseEncoding = Encoding.GetEncoding("UTF-8");
                                //}
                            }

                            using (StreamReader sReader = new StreamReader(httpResponse.GetResponseStream(), responseEncoding))
                            {
                                _result = sReader.ReadToEnd();
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Thread.Sleep(1000);
                    }
                }
                while (loopCount <= timeToTry);
            }
            catch (Exception ex)
            {
            }
            return _result;
        }

        /// <summary>
        /// gọi api bằng cách kết nối socket
        /// </summary>
        /// <param name="url"></param>
        /// <param name="beginIndex"></param>
        /// <returns></returns>
        public static string HttpSocket(string url,int beginIndex)
        {
            string hostName=url.Substring(7, url.IndexOf(":",7)-7);
            int port = int.Parse(url.Substring(url.IndexOf(":", url.IndexOf(":") + 1) + 1, url.IndexOf("/",url.IndexOf(":")+3)-url.IndexOf(":", url.IndexOf(":") + 1)-1));            
            try
            {
                string result = "";
                TcpClient client = new TcpClient();
                client.SendTimeout = 10000;
                client.Connect(hostName, port);
                Stream stream = client.GetStream();
                ASCIIEncoding encoding = new ASCIIEncoding();
                // 2. send
                string message = "GET " + url.Substring(beginIndex);
                byte[] data = encoding.GetBytes(message);

                stream.Write(data, 0, data.Length);

                // 3. receive
                data = new byte[1024];
                stream.Read(data, 0, 1024);
                result = encoding.GetString(data);
                stream.Close();
                client.Close();
                return result;
               
            }

            catch (Exception ex)
            {
                //WebDB.write("", ex.Message);
                return "";
            }
        }
    }
}
